package com.nari.ncps.screen.controller;

import cn.hutool.core.date.DateUtil;
import com.nari.ncps.screen.common.pojo.ApiResponse;
import com.nari.ncps.screen.entity.electric.ElectricOpermonEquipFix;
import com.nari.ncps.screen.entity.electric.ElectricProdoperCoalConsumeLr;
import com.nari.ncps.screen.entity.electric.ElectricSafetyenvPollutant;
import com.nari.ncps.screen.service.electric.*;
import com.nari.ncps.screen.service.wholeproduct.QtDpIndustryProfileService;
import com.nari.ncps.screen.vo.electric.*;
import com.nari.ncps.screen.vo.wholeproduct.IndustryProfileVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 火电 前端控制器
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Tag(name = "火电产业", description = "火电产业")
@RestController
@RequestMapping("/electric")
public class ElectricController {

    // 火电-生产经营-发电情况 service
    @Resource
    private ElectricProdoperPowerGeneralService electricProdoperPowerGeneralService;
    @Resource
    private ElectricProdoperHeatingService electricProdoperHeatingService;
    @Resource
    private ElectricProdoperFuelService electricProdoperFuelService;
    @Resource
    private ElectricProdoperFuelFromService electricProdoperFuelFromService;
    @Resource
    private ElectricProdoperCoalConsumeLrService electricProdoperCoalConsumeLrService;
    @Resource
    private ElectricProdoperCoalConsumeUrService electricProdoperCoalConsumeUrService;
    @Resource
    private ElectricProdoperCoalConsumeService electricProdoperCoalConsumeService;
    @Resource
    private ElectricOpermonEquipFixService electricOpermonEquipFixService;
    @Resource
    private ElectricOverviewItemService electricOverviewItemService;
    @Resource
    private ElectricOpermonEquipUseService electricOpermonEquipUseService;
    @Resource
    private ElectricOpermonPlantService electricOpermonPlantService;
    @Resource
    private ElectricSafetyenvPollutantService electricSafetyenvPollutantService;
    @Resource
    private ElectricSafetyenvPlantRtService electricSafetyenvPlantRtService;
    @Resource
    private ElectricRealTimeDataService electricRealTimeDataService;

    /**
     * 发电计划完成情况
     * @param year 年份（选填，默认当前年）
     * @param month 月份（选填，默认当前月）
     * @return 发电计划完成情况
     */
    @Operation(summary = "发电计划完成情况", description = "发电计划完成情况，参数可不传，默认查询当前年月数据")
    @GetMapping("/prodoper/generation/plan-completion")
    public ApiResponse<FdPlanCompletionStatus> fdPlanCompletionStatus(
            @RequestParam(value = "year", required = false) Integer year,
            @RequestParam(value = "month", required = false) Integer month) {

        FdPlanCompletionStatus status = electricProdoperPowerGeneralService.fdPlanCompletionStatus(year, month);
        return ApiResponse.succeed(status);
    }

    /**
     * 发电计划完成情况趋势图
     * @param year 年份（选填，默认当前年）
     * @return 包含今年和去年各月份发电量的趋势列表
     */
    @Operation(summary = "发电计划完成情况趋势图", description = "查询指定年份及去年所有月份的发电量完成情况统计趋势图，参数可不传，默认使用当前年")
    @GetMapping("/prodoper/generation/trend")
    public ApiResponse<List<FdComplateTrend>> complateTrend(
            @RequestParam(value = "year", required = false) Integer year) {
        List<FdComplateTrend> trendList =
                electricProdoperPowerGeneralService.fdComplateTrend(year);
        return ApiResponse.succeed(trendList);
    }

    /**
     * 各个电厂供电完成情况
     * @param year
     * @return
     */
    @Operation(summary = "各个电厂供电完成情况", description = "各个电厂供电完成情况")
    @GetMapping("/electric/prodoper/generation/plant-completion")
    public ApiResponse<List<FdPowerPlantSupplyComplateStatus>> powerPlantSupplyComplateStatus(
            @RequestParam(value = "year", required = false) Integer year) {

        System.out.println("======== 各个电厂供电完成情况查询 ========");
        System.out.println("查询年份: " + (year != null ? year : "未指定"));

        if(year == null) {
            year = LocalDate.now().getYear();
        }

        List<FdPowerPlantSupplyComplateStatus> statusList =
                electricProdoperPowerGeneralService.fdPowerPlantSupplyComplateStatus(year);
        return ApiResponse.succeed(statusList);
    }

    /**
     * 供热计划完成情况
     * @param year 年份（选填，默认当前年）
     * @param month 月份（选填，默认当前月）
     * @return 供热计划完成情况
     */
    @Operation(summary = "供热计划完成情况", description = "供热计划完成情况，参数可不传，默认查询当前年月数据。数据从qt_dp_electric_prodoper_heating表查询，根据date_type区分年数据(0)和月数据(1)，多条数据自动求和")
    @GetMapping("/prodoper/heating/plan-completion")
    public ApiResponse<GrPlanCompletionStatus> grPlanCompletionStatus(
            @RequestParam(value = "year", required = false) Integer year,
            @RequestParam(value = "month", required = false) Integer month) {
        GrPlanCompletionStatus status =
                electricProdoperHeatingService.grPlanCompletionStatus(year, month);
        return ApiResponse.succeed(status);
    }

    /**
     * 供热计划完成情况趋势图
     * @param year 年份（选填，默认当前年）
     * @return 包含今年和去年各月份供热量的趋势列表
     */
    @Operation(summary = "供热计划完成情况趋势图", description = "查询指定年份及去年所有月份的供热量完成情况统计趋势图，参数可不传，默认使用当前年。数据从qt_dp_electric_prodoper_heating表查询，根据date_type=1查询月数据，相同月份自动求和")
    @GetMapping("/prodoper/heating/trend")
    public ApiResponse<List<GrComplateTrend>> grComplateTrend(@RequestParam(value = "year", required = false) Integer year) {
        List<GrComplateTrend> status =electricProdoperHeatingService.grComplateTrend(year);
        return ApiResponse.succeed(status);
    }


    /**
     * 各个电厂供热完成情况
     * @param year 年份（选填，默认当前年）
     * @return 各个电厂的年度供热完成情况列表
     */
    @Operation(summary = "各个电厂供热完成情况", description = "查询各个电厂的年度供热完成情况，参数可不传，默认查询当前年数据。数据从qt_dp_electric_prodoper_heating表查询，根据date_type=0查询年数据，相同电厂相同年份的数据自动求和")
    @GetMapping("/prodoper/heating/plant-completion")
    public ApiResponse<List<GrPowerPlantSupplyComplateStatus>> grPlanCompletionStatus(
            @RequestParam(value = "year", required = false) Integer year) {
        List<GrPowerPlantSupplyComplateStatus> statusList =
                electricProdoperHeatingService.grPowerPlantSupplyComplateStatus(year);
        return ApiResponse.succeed(statusList);
    }

    /**
     * 燃料进耗存情况
     * @param year 年份（选填，默认当前年）
     * @return 燃料进耗存情况
     */
    @Operation(summary = "燃料进耗存情况", description = "燃料进耗存情况，参数可不传，默认查询当前年月数据。数据从qt_dp_electric_prodoper_fuel表查询，年数据根据date_type=0查询，月数据根据date_type=1查询，多条数据自动求和")
    @GetMapping("/prodoper/fuel/inventory")
    public ApiResponse<InventorySituation> inventorySituation(
            @RequestParam(value = "year", required = false) Integer year) {
        // 如果year为空，设置为当前年
        if (year == null) {
            year = DateUtil.year(new Date());
        }

        InventorySituation situation =
                electricProdoperFuelService.inventorySituation(year);
        return ApiResponse.succeed(situation);
    }

    /**
     * 各电厂存煤以及可用天数情况
     * @param year 年份（选填，默认当前年）
     * @return 各电厂各月份的存煤及可用天数列表
     */
    @Operation(summary = "各电厂存煤以及可用天数", description = "各电厂存煤以及可用天数，参数可不传，默认查询当前年数据。数据从qt_dp_electric_prodoper_fuel表查询，根据date_type=1查询月数据，相同电厂相同月份的数据自动求和")
    @GetMapping("/prodoper/fuel/coal-availability")
    public ApiResponse<List<CoalStorageAndAvailableDays>> coalStorageAndAvailableDays(
            @RequestParam(value = "year", required = false) Integer year) {
        // 如果year为空，设置为当前年
        if (year == null) {
            year = DateUtil.year(new Date());
        }

        List<CoalStorageAndAvailableDays> list = electricProdoperFuelService.coalStorageAndAvailableDays(year);
        return ApiResponse.succeed(list);
    }

    /**
     * 煤炭来源分布情况
     * @param year
     * @return
     */
    @Operation(summary = "煤炭来源分布情况", description = "煤炭来源分布情况")
    @GetMapping("/prodoper/fuel/source-distribution")
    public ApiResponse<List<CoalSourceDistribution>> distributionCoalSources(
            @RequestParam(value = "year", required = false) Integer year) {
        List<CoalSourceDistribution> list = electricProdoperFuelFromService.getCoalSourceDistributionByPlant(year);
        return ApiResponse.succeed(list);
    }

    /**
     * 火电生产实时负荷
     * @return
     */
    @Operation(summary = "火电生产实时负荷", description = "火电生产实时负荷")
    @GetMapping("/prodoper/coal-consumption/realtime-load")
    public ApiResponse<List<ElectricProdoperCoalConsumeLr>> prodoperCoalConsumelr() {
        List<ElectricProdoperCoalConsumeLr> list = electricProdoperCoalConsumeLrService.prodoperCoalConsume();
        return ApiResponse.succeed(list);
    }

    /**
     * 综合厂用电率概览
     * @param year 年份（可选，默认当前年）
     * @return PowerRateOverviewVO包含：yearAverage(全年平均厂用电率)、yoyChange(同比增加)、dataList(详细数据列表)
     */
    @Operation(summary = "生产经营-综合厂用电率", description = "获取电力产业综合厂用电率数据，包含全年平均用电率、同比变化和各月详细数据")
    @GetMapping("/prodoper/coal-consumption/power-rate")
    public ApiResponse<PowerRateOverviewVO> getPowerRateOverview(
            @RequestParam(value = "year", required = false) Integer year) {
        PowerRateOverviewVO overview = electricProdoperCoalConsumeUrService.getPowerRateOverview(year);
        if (overview != null) {
            List<PowerRateDataItemVO> dataList = overview.getDataList();
            if (!dataList.isEmpty()) {
                // 判断 dataList 如果大于 6 条，则返回 6 条
                if (dataList.size() > 6) {
                    dataList = dataList.subList(0, 6);
                }
                // 返回 dataList
                overview.setDataList(dataList);
                overview.setYearAverage(overview.getYearAverage());
                overview.setYoyChange(overview.getYoyChange());
                return ApiResponse.succeed(overview);
            }
        }
        return ApiResponse.succeed(new PowerRateOverviewVO());
    }

    /**
     * 供电煤耗趋势
     * @return 只包含年份、月份、当月总耗煤量、去年同期总耗煤量的DTO列表（按月汇总）
     */
    @Operation(summary = "供电煤耗趋势", description = "供电煤耗趋势，返回年份、月份、当月总耗煤量、去年同期总耗煤量（按月汇总）")
    @GetMapping("/prodoper/coal-consumption/trend")
    public ApiResponse<List<CoalConsumeTrendDto>> prodoperCoalConsume() {
        List<CoalConsumeTrendDto> result = electricProdoperCoalConsumeService.prodoperCoalConsume();
        return ApiResponse.succeed(result);
    }


    /**
     * 火电产业总览统计
     * @param year 年份（必填）
     * @return 统计后的总览数据，包含各项指标的总和
     */
    @Operation(summary = "主要关键指标", description = "根据年份、月份、日期统计火电产业各项指标数据")
    @GetMapping("/overview/key-metrics")
    public ApiResponse<ElectricOverviewDto> getOverviewStatistics(
            @RequestParam(value = "year", required = false) Integer year) {
        ElectricOverviewDto result = electricOverviewItemService.getOverviewStatistics(year);
        return ApiResponse.succeed(result);
    }

    /**
     * 设备状态检测
     * @param year 年份（必填）
     * @return 设备使用统计数据，包含机组总台数、装机总容量、运行台数等信息
     */
    @Operation(summary = "设备状态检测", description = "按年份统计设备使用情况，包含机组总台数量、装机总容量、机组运行台数、机组运行总容量、机组备用台数、机组备用总容量、机组检修台数、机组检修总容量")
    @GetMapping("/opermon/equipment-status")
    public ApiResponse<EquipmentUsageStatistics> getEquipmentUsageStatistics(
            @RequestParam(value = "year", required = false) Integer year) {
        EquipmentUsageStatistics result = electricOpermonEquipUseService.getEquipmentUsageStatistics(year);
        return ApiResponse.succeed(result);
    }


    /**
     * 机组检修监测
     * @param year
     * @return
     */
    @Operation(summary = "机组检修监测", description = "机组检修监测")
    @GetMapping("/opermon/unit-maintenance")
    public ApiResponse<List<ElectricOpermonEquipFix>> opermonEquip(
            @RequestParam(value = "year", required = false) Integer year) {
        List<ElectricOpermonEquipFix> list = electricOpermonEquipFixService.opermonEquip(year);
        return ApiResponse.succeed(list);
    }

    /**
     * 各电厂运行监测
     * @param year 年份（必填）
     * @return 各电厂容量统计数据，包含总容量、运行容量、停机容量、运行率
     */
    @Operation(summary = "各电厂运行监测", description = "按电厂维度统计每个电厂的总容量、运行容量、停机容量、运行率等指标")
    @GetMapping("/opermon/plant-operation")
    public ApiResponse<List<PlantCapacityStatistics>> getPlantCapacityStatistics(
            @RequestParam(value = "year", required = false) Integer year) {
        List<PlantCapacityStatistics> result = electricOpermonPlantService.getPlantCapacityStatistics(year);
        return ApiResponse.succeed(result);
    }

    /**
     * 污染物排放情况
     * 只返回最近6个月的数据
     * @param year 年份（选填，不传则自动计算最近6个月）
     * @return 月度排放量统计数据列表（最近6个月）
     */
    @Operation(summary = "污染物排放情况", description = "按月份统计二氧化碳、二氧化硫每个月的排放量（最近6个月）")
    @GetMapping("/safetyenv/pollutant-emission")
    public ApiResponse<List<MonthlyEmissionStatistics>> getMonthlyEmissionStatistics(
            @RequestParam(value = "year", required = false) Integer year) {
        List<MonthlyEmissionStatistics> resultList = electricSafetyenvPollutantService.getRecentSixMonthsEmission(year);
        return ApiResponse.succeed(resultList);
    }

    /**
     * 二氧化碳减排及节煤情况
     * @param year 年份（必填）
     * @return 月度减排效益统计数据列表
     */
    @Operation(summary = "二氧化碳减排及节煤情况", description = "按月份统计二氧化碳减排量、节煤量每个月的数据")
    @GetMapping("/safetyenv/co2-reduction")
    public ApiResponse<List<MonthlyReductionStatistics>> getMonthlyReductionStatistics(
            @RequestParam(value = "year", required = false) Integer year) {
        List<MonthlyReductionStatistics> resultList = electricSafetyenvPollutantService.getMonthlyReductionStatistics(year);
        return ApiResponse.succeed(resultList);
    }

    /**
     * 环保数据实时监测
     * @param year 年份（必填）
     * @return 电厂年度排放统计数据，包含公司、电厂、机组、状态、粉尘排放标准、硫化物排放标准、氮氧化物排放标准等信息
     */
    @Operation(summary = "环保数据实时监测", description = "根据传入年份按照电厂维度统计，统计每一个字段年累计，查询字段包括：公司、电厂、机组、状态、粉尘排放标准、硫化物排放标准、氮氧化物排放标准")
    @GetMapping("/safetyenv/realtime-monitoring")
    public ApiResponse<List<PlantAnnualEmissionStatistics>> getPlantAnnualEmissionStatistics(
            @RequestParam(value = "year", required = false) Integer year) {
        List<PlantAnnualEmissionStatistics> result = electricSafetyenvPlantRtService.getPlantAnnualEmissionStatistics(year);
        return ApiResponse.succeed(result);
    }

    /**
     * 查询单位简介信息
     * @param industryType 产业分类（选填）
     * @return 单位简介信息，包含单位编码、单位名称、图片、简介
     */
    @Operation(summary = "电厂简介", description = "根据产业分类、单位编码查询单位简介信息，如果参数不传则返回默认数据")
    @GetMapping("/industry-profile")
    public ApiResponse<IndustryProfileVO> getIndustryProfile(
            @RequestParam(value = "industryType", required = false) Integer industryType,
            @RequestParam(value = "orgCode", required = false) String orgCode) {

        // 创建一个默认的单位简介数据
        IndustryProfileVO profile = new IndustryProfileVO();
        if("134027".equalsIgnoreCase(orgCode)) {
            profile.setUnitName("盛发热电公司");
        } else if("134028".equalsIgnoreCase(orgCode)) {
            profile.setUnitName("通辽热电公司");
        } else if("134070".equalsIgnoreCase(orgCode)) {
            profile.setUnitName("通辽电投发电公司");
        } else if("180063".equalsIgnoreCase(orgCode)) {
            profile.setUnitName("内蒙大板火电厂");
        }  else if("134069".equalsIgnoreCase(orgCode)) {
            profile.setUnitName("内蒙赤峰热电厂");
        }

        return ApiResponse.succeed(profile);
    }

    /**
     * 查询电厂运行监测信息
     * @return 电厂运行监测信息，包含运行容量、停机台数、停运容量、装机容量、运行机组台数、利用小时数
     */
    @Operation(summary = "电厂基本信息", description = "根据单位编码查询电厂运行监测信息，如果参数不传则返回默认数据")
    @GetMapping("/opermon/plant-monitor")
    public ApiResponse<PlantOperationMonitorVO> getPlantOperationMonitor(
            @RequestParam(value = "orgCode", required = false) String orgCode) {
        PlantOperationMonitorVO monitor = electricRealTimeDataService.getPlantOperationMonitor(orgCode);

//        PlantOperationMonitorVO monitor = electricOpermonPlantService.getPlantOperationMonitor(orgCode);
//        PlantOperationMonitorVO monitor = new PlantOperationMonitorVO();
//        monitor.setInstalledCapacity(BigDecimal.valueOf(120));
//        monitor.setUtilizationHours(BigDecimal.ZERO);
        return ApiResponse.succeed(monitor);
    }

    /**
     * 查询生产情况信息
     * @return 生产情况信息，包含日发电量、日均煤耗、库存可用天数
     */
    @Operation(summary = "查询生产情况信息", description = "根据单位编码查询生产情况信息，如果参数不传则返回默认数据")
    @GetMapping("/prodoper/production-status")
    public ApiResponse<ProductionStatusVO> getProductionStatus(
            @RequestParam(value = "orgCode", required = false) String orgCode) {

        ProductionStatusVO status = electricProdoperFuelService.getProductionStatus(orgCode);
        return ApiResponse.succeed(status);
    }

    /**
     * 查询日供热量信息
     * @return 日供热量信息列表，返回一个月（31天）的数据
     */
    @Operation(summary = "查询日供热量信息", description = "根据单位编码查询日供热量信息，如果参数不传则返回默认数据（一个月31天的数据）")
    @GetMapping("/prodoper/industry-profile-heating")
    public ApiResponse<List<DailyHeatingVO>> getDailyHeating(
            @RequestParam(value = "orgCode", required = false) String orgCode) {

        List<DailyHeatingVO> heatingList = electricOverviewItemService.getDailyHeating(orgCode);
        return ApiResponse.succeed(heatingList);
    }

    private static void addRecord(List<DailyHeatingVO> list, String code, String name,
                                  Integer year, Integer month, Integer day, BigDecimal heating) {
        DailyHeatingVO vo = new DailyHeatingVO();
        vo.setPowerPlantCode(code);
        vo.setPowerPlantName(name);
        vo.setYear(year);
        vo.setMonth(month);
        vo.setDay(day);
        vo.setDailyActualHeating(heating);
        list.add(vo);
    }


    /**
     * 查询运行水平信息
     * @return 运行水平信息列表，返回20条分钟级别的数据
     */
    @Operation(summary = "查询运行水平信息", description = "根据单位编码查询运行水平信息（实时负荷、负荷率），如果参数不传则返回默认数据（20条分钟级别数据）")
    @GetMapping("/prodoper/operation-level")
    public ApiResponse<List<OperationLevelVO>> getOperationLevel(
            @RequestParam(value = "orgCode", required = false) String orgCode) {

        List<OperationLevelVO> levelList = electricProdoperCoalConsumeLrService.getOperationLevel(orgCode);
        return ApiResponse.succeed(levelList);
    }

    /**
     * 查询环保浓度监测信息
     * @return 环保浓度监测信息，包含二氧化硫、烟尘、氮氧化物的实时和历史浓度数据
     */
    @Operation(summary = "查询环保浓度监测信息", description = "根据单位编码查询环保浓度监测信息（二氧化硫、烟尘、氮氧化物的实时和历史数据），如果参数不传则返回默认数据")
    @GetMapping("/safetyenv/density-monitor")
    public ApiResponse<DensityMonitorVO> getDensityMonitor(
            @RequestParam(value = "orgCode", required = false) String orgCode) {

        // 创建一条环保浓度监测数据
        DensityMonitorVO monitor = new DensityMonitorVO();
        return ApiResponse.succeed(monitor);
    }




}
